package sword_offer;

/**
 * @ClassName _67strToInt
 * @Description: 注意：本题与主站 8 题相同：https://leetcode-cn.com/problems/string-to-integer-atoi/
 * @Author: yongliang.ma
 * @Create_time:2022/10/13 10:52
 */
// 题目来源：https://leetcode.cn/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/
public class _67strToInt {

    // 借助long类型来判断
    public int strToInt(String str) {
        if (str == null || str.length() == 0)
            return 0;
        int index = 0, sign = 1;
        long res = 0;
        while (str.charAt(index) == ' '){
            index++;
            if (index == str.length())
                return 0;
        }
        if (str.charAt(index) == '-'){
            sign = -1;
            index++;
        }else if (str.charAt(index) == '+'){
            index++;
        }
        for (int i = index; i < str.length(); i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9')
                break;
            res = res * 10 + (str.charAt(i) - '0');
            if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE)
                return sign == 1?Integer.MAX_VALUE : Integer.MIN_VALUE;
        }

        return sign * (int)res;
    }

    // 锁定范围，Integer.MAX_VALUE/10得到边界值，
    public int strToIntImprove(String str) {
        if (str == null || str.length() == 0)
            return 0;
        int index = 0, sign = 1, boundary = Integer.MAX_VALUE / 10;
        int res = 0;
        while (str.charAt(index) == ' '){
            index++;
            if (index == str.length())// 判断是否到达字符串末尾
                return 0;
        }
        if (str.charAt(index) == '-'){
            sign = -1;
            index++;
        }else if (str.charAt(index) == '+'){
            index++;
        }

        for (int i = index; i < str.length(); i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9')
                break;
            if (res > boundary || (res == boundary && str.charAt(i) - '7' > 0))
                return sign == 1?Integer.MAX_VALUE : Integer.MIN_VALUE;
            res = res * 10 + (str.charAt(i) - '0');// 由于使用int类型存储，所以需要在做乘法前边判断
        }

        return sign * res;
    }
}
